<?php
	$root = $_SERVER['DOCUMENT_ROOT'];
	include($root . "/util/session.php");//checks that the user is logged in
	include($root . "/util/privilege_check.php");
	checkPrivilege("admin");
	if($_SERVER["REQUEST_METHOD"] == "POST"){
		$degreeID=mysqli_real_escape_string($db,$_POST['degreeID']);

		$sql_query="select * from degrees where degreeID = '$degreeID'";
		$result=mysqli_query($db,$sql_query);
		//check if user exists
		if(mysqli_num_rows($result) == 0){
			$error="Degree doesn't exist";
		}
		else{
			$subjectID=mysqli_real_escape_string($db,$_POST['subjectID']);
			$subjectName=mysqli_real_escape_string($db,$_POST['subjectName']);
			$description=mysqli_real_escape_string($db,$_POST['description']);
			$coordinator=mysqli_real_escape_string($db,$_POST['coordinatorID']);
			$sql_query="INSERT INTO `subjects` (`degreeID`, `subjectID`, `subjectName`, `description`, `coordinatorID`) VALUES ('$degreeID', '$subjectID', '$subjectName', '$description', '$coordinator')";
			$result=mysqli_query($db,$sql_query);
			if($result){
				header("Location: /admin/admin.php?msg=Subject added");
			}
			else{
				$error="sql error";
			}
		}
	}
	else{
		$degreeID=mysqli_real_escape_string($db,$_GET['degreeID']);
	}
?>

<html>
<head>
	<title>Add a subject</title>
  	<link rel="stylesheet" type="text/css" href="adminStyle.css">
</head>
<body>
  	<?php
  	include($root . "/admin/header.php");
	?>
	<li><a href="/admin/degreeList.php">Back</a></li>
	<form action="/admin/subjectAdd.php" method="post" id="subjectForm">
		<label for="degreeID">Degree ID:</label><br>
		<input type="text" id="degreeID" name="degreeID" value="<?php echo $degreeID ?>"><br>
		<label for="subjectID">Subject ID:</label><br>
		<input type="text" id="subjectID" name="subjectID"><br>
		<label for="subjectName">Subject Name:</label><br>
		<input type="text" id="subjectName" name="subjectName"><br>
		<label for="description">Description:</label><br>
		<textarea rows="4" cols="50" name="description" id=description form="subjectForm"></textarea><br>
		<label for="coordinatorID">Coordinator:</label><br>
		<select name="coordinatorID" id="coordinatorID" name="coordinatorID" form="subjectForm">
			<?php
				$tSQL="select * from users join user_info on users.username=user_info.login where usertype='teacher'";
				$tResult=mysqli_query($db,$tSQL);
				while($teacher=mysqli_fetch_assoc($tResult)){
					echo '<option value="' . $teacher['username'] . '">' . $teacher['full_name'] . '</option>';
				}
			?>
		</select>
		<input type="submit" value="Submit">
	</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php if(isset($error)){echo $error;} ?></div>

	<?php
  	include($root . "/admin/footer.php");
	?>
</body>
</html>
